﻿<%@ WebHandler Language="C#" Class="riqihuizong_chart" %>

using System;
using System.Web;
using System.Data;
using KeaoBase;
using ServiceStack.Redis;
using System.Configuration;
using System.Collections.Generic;
using System.Text;


public class riqihuizong_chart : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            string uid = context.Request.QueryString["uid"];
            string kid = context.Request.QueryString["kid"];
            if (!Auth.UserLogined(uid, kid))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            string key = KeaoUtils.GetMD5Str(context.Request.Url.OriginalString.Replace(uid,"cache").Replace(kid,"cache"));
            using (IRedisClient redis = RedisClientPool.GetReadOnlyRedisClient())
            {
                if (redis != null)
                {
                    if (redis.ContainsKey(key))
                    {
                        context.Response.Write(redis.GetValue(key));
                        return;
                    }
                }
            }

            string zhanDian = context.Request.QueryString["zhandian"];
            string chengZhongLeiXing = context.Request.QueryString["chengzhongleixing"];
            string kaiShiShiJian = context.Request.QueryString["kaishishijian"];
            string jieShuShiJian = context.Request.QueryString["jieshushijian"];
            string wuliaomingcheng = context.Request.QueryString["wuliaomingcheng"];
            string xinghao = context.Request.QueryString["xinghao"];
            if (string.IsNullOrEmpty(zhanDian) || string.IsNullOrEmpty(chengZhongLeiXing) || string.IsNullOrEmpty(kaiShiShiJian) || string.IsNullOrEmpty(jieShuShiJian)||string.IsNullOrEmpty(wuliaomingcheng)||string.IsNullOrEmpty(xinghao))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            BaseDataBase m_DB = System.Reflection.Assembly.Load("KeaoDataBase").CreateInstance(string.Format("KeaoDataBase.{0}", ConfigurationManager.AppSettings["数据库类型"])) as BaseDataBase;
            if (!m_DB.InitDataBase(ConfigurationManager.ConnectionStrings["DataSource"].ConnectionString))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            else
            {
                string tableCols = string.Empty;
                string groupCols = string.Empty;
                DateTime kaiShiDate = DateTime.Parse(kaiShiShiJian);
                DateTime jieShuDate = DateTime.Parse(jieShuShiJian).AddHours(23).AddMinutes(59).AddSeconds(59);

                string createCondition = m_DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, chengZhongLeiXing, "", SearchConditionType.等于);
                if (chengZhongLeiXing == "入库物料")
                {
                    createCondition += m_DB.CreateAndCondition("pizhongshijian", DataValueCommonType.日期时间, kaiShiDate.ToString("yyyy-MM-dd HH:mm:ss"),jieShuDate.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
                    tableCols = string.Format("{0} as riqi,wuliaomingcheng,xinghao,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang", m_DB.DateFormatFun("pizhongshijian"));
                    groupCols = string.Format("{0},wuliaomingcheng,xinghao", m_DB.DateFormatFun("pizhongshijian"));
                }
                else
                {
                    createCondition += m_DB.CreateAndCondition("maozhongshijian", DataValueCommonType.日期时间, kaiShiDate.ToString("yyyy-MM-dd HH:mm:ss"), jieShuDate.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
                    tableCols = string.Format("{0} as riqi,wuliaomingcheng,xinghao,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang", m_DB.DateFormatFun("maozhongshijian"));
                    groupCols = string.Format("{0},wuliaomingcheng,xinghao", m_DB.DateFormatFun("maozhongshijian"));
                }

                if (!string.IsNullOrEmpty(zhanDian) && zhanDian != "—全部—")
                {
                    createCondition += m_DB.CreateAndCondition("zhandian", DataValueCommonType.字符串,zhanDian,"", SearchConditionType.等于);
                }
                if (!string.IsNullOrEmpty(wuliaomingcheng) && wuliaomingcheng != "—全部—")
                {
                    createCondition += m_DB.CreateAndCondition("wuliaomingcheng", DataValueCommonType.字符串, wuliaomingcheng, "", SearchConditionType.等于);
                }
                if (!string.IsNullOrEmpty(xinghao) && xinghao != "—全部—")
                {
                    createCondition += m_DB.CreateAndCondition("xinghao", DataValueCommonType.字符串, xinghao, "", SearchConditionType.等于);
                }
                Dictionary<string, string> orderBy = new Dictionary<string, string>();
                orderBy.Add("wuliaomingcheng", "asc");
                DataTable Dt = m_DB.GetDataTableByCondition("tbl_chengzhong", tableCols, null, createCondition, groupCols,orderBy);
                tableCols = "wuliaomingcheng,xinghao,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang";
                groupCols = "wuliaomingcheng,xinghao";
                DataTable DtCount = m_DB.GetDataTableByCondition("tbl_chengzhong", tableCols, null, createCondition, groupCols, orderBy);

                StringBuilder legendBuilder = new StringBuilder();
                StringBuilder xAxisBuilder = new StringBuilder();
                List<ChartLine> chartLines= new List<ChartLine>();
                if (Dt.Rows.Count > 0)
                {
                    legendBuilder.Append("\"legend\":[");
                    xAxisBuilder.Append("\"x\":[");
                    foreach (DataRow row in DtCount.Rows)
                    {
                        ChartLine chartParam = new ChartLine();
                        chartParam.WuLiaoMingCheng = string.Format("{0}", row["wuliaomingcheng"]);
                        chartParam.XingHao = string.Format("{0}", row["xinghao"]);
                        if (string.IsNullOrEmpty(chartParam.XingHao))
                        {
                            chartParam.SeriesName = string.Format("{0}", row["wuliaomingcheng"]);
                            legendBuilder.Append(string.Format("\"{0}\",", row["wuliaomingcheng"]));
                        }
                        else
                        {
                            chartParam.SeriesName = string.Format("{0}_{1}", row["wuliaomingcheng"], row["xinghao"]);
                            legendBuilder.Append(string.Format("\"{0}_{1}\",", row["wuliaomingcheng"], row["xinghao"]));
                        }
                        chartLines.Add(chartParam);
                    }
                    while (kaiShiDate < jieShuDate)
                    {
                        xAxisBuilder.Append(string.Format("\"{0}\",", kaiShiDate.ToString("yyyy-MM-dd")));
                        foreach (ChartLine charParam in chartLines)
                        {
                            DataRow[] rows = Dt.Select(string.Format(" riqi='{0}' and wuliaomingcheng='{1}' and xinghao='{2}'",kaiShiDate.ToString("yyyy-MM-dd"),charParam.WuLiaoMingCheng,charParam.XingHao));
                            if (rows.Length == 0)
                            {
                                charParam.SeriesData.Append("0,");
                            }
                            else
                            {
                                charParam.SeriesData.Append(string.Format("{0},", rows[0]["jingzhong"]));
                            }
                        }
                        kaiShiDate = kaiShiDate.AddDays(1);
                    }
                    legendBuilder.Remove(legendBuilder.Length-1, 1);
                    xAxisBuilder.Remove(xAxisBuilder.Length-1, 1);
                    legendBuilder.Append("]");
                    xAxisBuilder.Append("]");
                    StringBuilder seriesBuilder = new StringBuilder();
                    foreach (ChartLine chartLine in chartLines)
                    {
                        seriesBuilder.Append(chartLine.ToString());
                        seriesBuilder.Append(",");
                    }
                    seriesBuilder.Remove(seriesBuilder.Length - 1, 1);
                    string responseJson = string.Format("{0}{1},{2},\"data\":[{3}]{4}", "{", legendBuilder.ToString(), xAxisBuilder.ToString(), seriesBuilder.ToString(), "}");
                    using (IRedisClient redis = RedisClientPool.GetRedisClient())
                    {
                        if (redis != null)
                        {
                            redis.SetValue(key, responseJson, TimeSpan.FromMinutes(10.0));
                        }
                    }

                    context.Response.Write(responseJson);
                }
                else
                {
                    context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                }

            }

        }
        catch (Exception err)
        {
            KeaoUtils.LogTxt(string.Format("查询日期汇总图表异常。{0}", err.Message));
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}